package com.cherry.web.controller.system;

import com.cherry.common.constant.UserConstants;
import com.cherry.common.core.controller.BaseController;
import com.cherry.common.core.domain.AjaxResult;
import com.cherry.common.core.page.TableDataInfo;
import com.cherry.common.core.text.Convert;
import com.cherry.common.enums.OnlineStatus;
import com.cherry.common.utils.ShiroUtils;
import com.cherry.framework.shiro.session.OnlineSession;
import com.cherry.framework.shiro.session.OnlineSessionDAO;
import com.cherry.system.domain.SysUserOnline;
import com.cherry.system.service.ISysUserOnlineService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * 在线用户 控制层
 *
 * @Author: 孙晨阳
 * @Date: 2023/3/2  22:31
 * @Version 1.0
 */
@Controller
@RequestMapping("/system/online")
public class SysUserOnlineController extends BaseController {

    private static final String PREFIX = "system/online";

    @Resource
    private ISysUserOnlineService userOnlineService;

    @Resource
    private OnlineSessionDAO onlineSessionDAO;

    /**
     * 跳转至在线用户页面
     *
     * @return 在线用户页面
     */
    @GetMapping()
    public String online() {
        return PREFIX + "/online";
    }

    /**
     * 查询在线用户列表
     *
     * @param userOnline
     * @return
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysUserOnline userOnline) {
        startPage();
        List<SysUserOnline> list = userOnlineService.selectUserOnlineList(userOnline);
        return getDataTable(list);
    }

    /**
     * 批量强退用户
     *
     * @param ids 用户ID
     * @return 结果
     */
    @PostMapping("/batchForceLogout")
    @ResponseBody
    public AjaxResult batchForceLogout(String ids) {

        for (String sessionId : Convert.toStrArray(ids)) {
            SysUserOnline online = userOnlineService.selectOnlineById(sessionId);
            if (online == null) {
                return error("用户已下线！");
            }

            OnlineSession onlineSession = (OnlineSession) onlineSessionDAO.readSession(online.getSessionId());
            if (onlineSession == null) {
                return error("用户已下线！");
            }

            if (sessionId.equals(ShiroUtils.getSessionId())) {
                return error("当前登录用户无法强退！");
            }

            if (online.getLoginName().equals(UserConstants.SYS_ADMIN)) {
                return error("不能强退超级管理员！");
            }

            onlineSessionDAO.delete(onlineSession);
            online.setStatus(OnlineStatus.OFF_LINE);
            userOnlineService.saveOnline(online);
            userOnlineService.removeUserCache(online.getLoginName(), sessionId);
        }
        return success();
    }
}
